package com.spring.boot.util;

import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

/**
 * @AUTHOR: 小于
 * @DATE: [2021/9/26  19:07]
 * @DESC:
 *
 *
 *
 *
 */
public class CookieUtils {
    public static String getCookieValue(HttpServletRequest request, String cookieName) {
        return getCookieValue(request, cookieName, false);
    }

    public static String getCookieValue(HttpServletRequest request, String cookieName, boolean isDecode) {
        Cookie[] cookies = request.getCookies();
        if (cookies == null || StringUtils.isBlank(cookieName)) {
            return null;
        }
        for (Cookie cookie : cookies) {
            if (cookie != null && StringUtils.equals(cookie.getName(), cookieName)) {
                if (isDecode) {
                    try {
                        return URLDecoder.decode(cookie.getValue(), "UTF-8");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    return cookie.getValue();
                }
            }
        }
        return null;
    }

    public static String getCookieValue(HttpServletRequest request, String cookieName, String encodeName) {
        Cookie[] cookies = request.getCookies();
        if (cookies == null || StringUtils.isBlank(cookieName)) {
            return null;
        }
        for (Cookie cookie : cookies) {
            if (cookie != null && StringUtils.equals(cookie.getName(), cookieName)) {
                if (StringUtils.isNotBlank(encodeName)) {
                    try {
                        return URLDecoder.decode(cookie.getValue(), encodeName);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    return cookie.getValue();
                }
            }
        }
        return null;
    }
}
